# Create your views here.
from django.template import Context, loader, RequestContext
from pool_v2.models import Player, Game, Pick, Week, UserProfile, Result, winner
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse



# views
def login_view(request):
    return render_to_response('login.html',
                              {'foo' : 'bar'},
                              context_instance=RequestContext(request))
    

def login_1(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('pool_v2.views.league_by_month'))
            # Redirect to a success page.
        else:
            raise Http404
    else:
        # Return an 'invalid login' error message.
        return HttpResponse("Invalid Login")

# League display using the wins/losses on the player object
def league(request):
    player_list = Player.objects.all().order_by('wins').reverse()
    player = request.user.get_profile().player
    weeks = Week.objects.all().order_by('date')
    t = loader.get_template('league.html')
    c = Context ({'player_list' : player_list,
                  'user_player' : player,
                  'weeks' : weeks})
    return HttpResponse(t.render(c))

# computes the records from all the results and displays them by month
def league_by_month(request):
    standings = gen_league_tables()
    player = request.user.get_profile().player
    weeks = Week.objects.all().order_by('date')
    t = loader.get_template('league_by_month.html')
    c = Context ({'standings' : standings,
                  'user_player' : player,
                  'weeks' : weeks})
    return HttpResponse(t.render(c))

    

def gen_league_tables():
    ret = []
    #May need to make sure all_months() is sorted in the future
    for date in all_months():
        wins, losses, draws = init_rec_hash()
        for result in results_in_month(date.month):
            cover = winner(result)
            for pick in Pick.objects.filter(game = result.game):
                if pick.pick == cover:
                    wins[pick.player] += 1
                elif cover != 'DRAW':
                    losses[pick.player] += 1
                else:
                    draws[pick.player] += 1
        ret.append([monthyear(date), standings_from_hash(wins, losses, draws)])
    return ret

#produces a string rep for the month year of the date
def monthyear(date):
    return str(date.month) + '/' + str(date.year)


# returns a list of the form [player wins losses draws]
def standings_from_hash(wins, losses, draws):
    return sorted([[player, wins[player], losses[player], draws[player]] 
                   for player in Player.objects.all()] ,
                  key=lambda a: a[1],
                  reverse=True)

           


# Creates three hash tables where the keys 
# are the players and the values are 0
def init_rec_hash():
    win = {}
    loss = {}
    draw = {}
    for player in Player.objects.all():
        win[player]=0
        loss[player]=0
        draw[player]=0
    return win,loss,draw

def results_in_month(month):
    return Result.objects.filter(game__week__date__month=month)

#returns a sorted list of date objects, one per month
def all_months():
    return map(lambda month : 
               sorted(Week.objects.filter(date__month=month))[0].date
               ,
               list(set(map(lambda x: x.date.month, Week.objects.all()))))

# Make_Picks
def make_picks(request, week_id, player_id):
    week = Week.objects.get(id=week_id)
    game_list = Game.objects.filter(week=week)
    player_picks = Pick.objects.filter(game__week__id=week_id,player__id=player_id)
    # We nee a check here to see if the games have already started
    # We will just do something stupid and not let anyone enter any picks after
    # 7pm Eastern Standard Time.
#    import pdb; pdb.set_trace()

    if player_picks.exists():
        return HttpResponse("You already made picks for this week")
    else:
        return render_to_response('make_picks.html',
                                  {'game_list' : game_list,
                                   'player_id' :player_id,
                                   'week' : week},
                                  context_instance=RequestContext(request))

# determines if the week is closed to new wagers
# In the future, it would be worthwhile to have a time based approach
def week_closed(week):
    return week.date < week.date.today()

    
# submit_picks
def submit_picks(request, player_id, week_id):
    week = get_object_or_404(Week, pk=week_id)
    player = get_object_or_404(Player, pk=player_id)
    games_list = Game.objects.filter(week=week)
    #Pick.objects.filter(game__week__id=week_id,player__id=player_id).delete()
    #print Pick.objects.filter(game__week__id=week_id,player__id=player_id).count() == 0
    if Pick.objects.filter(game__week__id=week_id,player__id=player_id).count() != 0:
        print 'crap'
        return HttpResponseRedirect(reverse('pool_v2.views.league_by_month'))

    picks = []
    
    for game in games_list:
        picked_team = request.POST[str(game.id)]
        pick = Pick(game=game, player=player, pick=picked_team)
        pick.save()
        picks.append(pick)
    
    picks_table = picks_for_week(week)

    return render_to_response('review_picks.html',
                              {'week' : week,
                               'picks_table' : picks_table},
                              context_instance=RequestContext(request))


#Add column here if there are results
def picks_for_week(week):
    ret = [['game']] 
    games_list = Game.objects.filter(week=week)
    players = Player.objects.all()
    for player in players:
        ret[0].append(player.name)
    for game in games_list:
        results = Result.objects.filter(game=game)
        if results:
            entry = [str(results[0])]
        else:
            entry = [str(game)]
        for player in players:
            pick = Pick.objects.filter(game=game,player=player)
            if len(pick) == 1:
                entry.append(pick[0].pick)
            else:
                entry.append('---')
        ret.append(entry)
    return ret
        


# submit_picks
def review_picks(request, player_id, week_id):
    week = get_object_or_404(Week, pk=week_id)
    player_picks = Pick.objects.filter(game__week__id=week_id,player__id=player_id)
    winners = map(winner,Result.objects.filter(game__week__id=week_id))
    
    #If there are results for this week, we should display them
    
    if not player_picks.exists():
        return HttpResponse("You need to make picks before you can review them")
    else:
        picks_table = picks_for_week(week)
        return render_to_response('review_picks.html',
                                  {'week' : week,
                                   'picks_table' : picks_table,
                                   'winners' : winners},
                                  context_instance=RequestContext(request))
    


# enter_results
def enter_results(request, week_id):
    week = Week.objects.get(id=week_id)
    game_list = Game.objects.filter(week=week)
    if request.user.username == 'klenk':
        return render_to_response('enter_results.html',
                                  {'game_list' : game_list,
                                   'week' : week},
                                  context_instance=RequestContext(request))
    else:
        return HttpResponse("Only Klenk is allowed to enter results")

    
# submit_results
def submit_results(request, week_id):
    week = get_object_or_404(Week, pk=week_id)
    games_list = Game.objects.filter(week=week)
    Result.objects.filter(game__week__id=week_id).delete()
    
    for game in games_list:
        home = request.POST['home_' + str(game.id)]
        away = request.POST['away_' + str(game.id)]
        result = Result(game=game, home_score=int(home), away_score=int(away)) 
        result.save()

# It would be nice to see a summary of the week displayed here.
    return HttpResponseRedirect(reverse('pool_v2.views.league_by_month'))


